//
//  ViewController.m
//  CI_Test
//
//  Created by admin on 2017/10/28.
//  Copyright © 2017年 WildOne. All rights reserved.
//

#import "ViewController.h"
#import "GCDAsyncSocket.h"




@protocol MyChatServertDelegate <NSObject>
-(void)ssss:(GCDAsyncSocket *)sock data:(NSData*)data;
-(void)ssss2:(GCDAsyncSocket *)sock data:(NSData*)data;
@end



@interface MyChatServer : NSObject<GCDAsyncSocketDelegate>
{
    GCDAsyncSocket *_serverSocket;
    dispatch_queue_t _golbalQueue;
}
@property(strong,nonatomic)NSMutableArray *clientSocket;
@property(nonatomic,assign)id<MyChatServertDelegate> delegate;
/**
 *  开启聊天服务器
 */
-(void)startServer;
@end
@implementation MyChatServer

-(void)startServer{
    //打开监听端口
    NSError *err;
    //    [_serverSocket connectToHost:@"127.0.0.1" onPort:12345 error:&err];
    [_serverSocket acceptOnPort:5011 error:&err];
    if (!err) {
        NSLog(@"服务开启成功");
    }else{
        NSLog(@"服务开启失败");
    }
}

-(instancetype)init{
    if (self = [super init]) {
        _clientSocket = [NSMutableArray array];
        //创建全局queue
        _golbalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //创建服务端的socket，注意这里的是初始化的同时已经指定了delegate
        _serverSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:_golbalQueue];
    }
    return self;
}





#pragma mark 有客户端建立连接的时候调用
-(void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket{
    //sock为服务端的socket，服务端的socket只负责客户端的连接，不负责数据的读取。   newSocket为客户端的socket
    NSLog(@"服务端的socket %p 客户端的socket %p",sock,newSocket);
    //保存客户端的socket，如果不保存，服务器会自动断开与客户端的连接（客户端那边会报断开连接的log）
    [self.clientSocket removeAllObjects];
    [self.clientSocket addObject:newSocket];
    
    //newSocket为客户端的Socket。这里读取数据
    [newSocket readDataWithTimeout:-1 tag:100];
    
//    [newSocket readDataToData:[GCDAsyncSocket CRLFData]
//                    withTimeout:30
//                      maxLength:8190
//                            tag:10];
    
    
    NSString*respons=@"Request URL:http://192.168.1.105:5011\nRequest Method:GET\nStatus Code:200 OK\nRemote Address:192.168.1.105:5011\nReferrer Policy:no-referrer-when-downgrade\n";
    respons=[NSString stringWithFormat:@"%@Accept:image/webp,image/apng,image/*,*/*;q=0.8\n",respons];
    respons=[NSString stringWithFormat:@"%@Accept-Encoding:gzip, deflate\nAccept-Language:zh-CN,zh;q=0.8\n",respons];
    respons=[NSString stringWithFormat:@"%@Connection:keep-alive\nHost:192.168.1.105:5011\nReferer:http://192.168.1.105:5011/qweqw\n",respons];
    respons=[NSString stringWithFormat:@"%@User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\n",respons];
    
    respons=[NSString stringWithFormat:@"%@{ip:'223.156.210.135',address:'湖南省 电信'}",respons];
    //[newSocket writeData:[respons dataUsingEncoding:NSUTF8StringEncoding] withTimeout:30 tag:100];
    
    
    if (self.delegate) {
        [self.delegate ssss2:newSocket data:newSocket.userData];
    }
}


#pragma mark 服务器写数据给客户端
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
    [sock readDataWithTimeout:-1 tag:100];
}

#pragma mark 接收客户端传递过来的数据
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    
    //sock为客户端的socket
    NSLog(@"客户端的socket %p",sock);
    //接收到数据
    NSString *receiverStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"length:%ld",receiverStr.length);
    // 把回车和换行字符去掉，接收到的字符串有时候包括这2个，导致判断quit指令的时候判断不相等
    receiverStr = [receiverStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    receiverStr = [receiverStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    //判断是登录指令还是发送聊天数据的指令。这些指令都是自定义的
    //登录指令
    [sock writeData:[@"asd" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    if([receiverStr hasPrefix:@"Host:"]){
        // 获取用户名
        [sock writeData:[@"asd" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    }
    //聊天指令
    if ([receiverStr hasPrefix:@"msg:"]) {
        //截取聊天消息
        NSString *msg = [receiverStr componentsSeparatedByString:@":"][1];
        [sock writeData:[msg dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:0];
    }
    //quit指令
    if ([receiverStr isEqualToString:@"quit"]) {
        //断开连接
        [sock disconnect];
        //移除socket
        [self.clientSocket removeObject:sock];
    }
    
    if (self.delegate) {
        
        [self.delegate ssss:sock data:data];
    }
}


@end

@interface ViewController ()<MyChatServertDelegate>
@property (nonatomic, strong) MyChatServer *chatServer;
@property (weak, nonatomic) IBOutlet UITextField *textfield;
@property (weak, nonatomic) IBOutlet UIWebView *webview;
@property (weak, nonatomic) IBOutlet UILabel *lb1;
@property (weak, nonatomic) IBOutlet UILabel *lb2;
 

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    _chatServer = [[MyChatServer alloc] init];
//    _chatServer.delegate=self;
//    [_chatServer startServer];
    
    
    // Do any additional setup after loading the view, typically from a nib.
}

- (IBAction)TEST:(UIButton *)sender {
    GCDAsyncSocket*dd=[_chatServer.clientSocket firstObject];
    
    
    NSDictionary *dic=@{
                        @"Request URL":@"http://192.168.1.105:5011",
                        @"Request Method":@"GET",
                        @"Status Code":@"200",
                        @"Remote Address":@"192.168.1.105:5011",
                        @"Referrer Policy":@"no-referrer-when-downgrade",
                        @"Accept":@"image/webp,image/apng,image/*,*/*;q=0.8",
                        @"Connection":@"keep-alive",
                        };
    
    
    //NSData *data =   [NSJSONSerialization dataWithJSONObject:dicoptions:NSJSONWritingPrettyPrintederror:nil];
    
    NSString*respons=@"Request URL:http://192.168.1.105:5011\nRequest Method:GET\nStatus Code:200 OK\nRemote Address:192.168.1.105:5011\nReferrer Policy:no-referrer-when-downgrade\n";
    respons=[NSString stringWithFormat:@"%@Accept:image/webp,image/apng,image/*,*/*;q=0.8\n",respons];
    respons=[NSString stringWithFormat:@"%@Accept-Encoding:gzip, deflate\nAccept-Language:zh-CN,zh;q=0.8\n",respons];
    respons=[NSString stringWithFormat:@"%@Connection:keep-alive\nHost:192.168.1.105:5011\nReferer:http://192.168.1.105:5011/qweqw\n",respons];
    respons=[NSString stringWithFormat:@"%@User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36\n",respons];
    
    respons=[NSString stringWithFormat:@"%@{ip:'223.156.210.135',address:'湖南省 电信'}",respons];
    
    respons=@"{ip:'223.156.210.135',address:'湖南省 电信'}";
    [dd writeData:[respons dataUsingEncoding:NSUTF8StringEncoding] withTimeout:30 tag:100];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)ssss:(GCDAsyncSocket *)sock data:(NSData*)data;
{
    if (!data) {
        return;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        _lb1.text=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
    });
}
-(void)ssss2:(GCDAsyncSocket *)sock data:(NSData*)data;
{
    if (!data) {
    return;
}
    dispatch_async(dispatch_get_main_queue(), ^{
         _lb2.text=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
    });
    
  
}

@end
